package configuration;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

import userInterface.MainPage;

import main.Main;

import field_REGEX_Definitions.CustomField;
import fields.FieldMatcher;

public class UserFields_XmlWriter {
	
	/**
	 * Initializes and writes xml output to file "DBASE.xml".
	 */
	public UserFields_XmlWriter(String type) {
		String programDirectory = "C:\\Users\\"+System.getProperty("user.name")+"\\Documents\\WVU PII Parser\\source\\";
		String userFields_outfile = programDirectory+"configuration_files\\custom_fields.xml";
		String keywordSearch_outfile = programDirectory+"configuration_files\\search_words.xml";
		try {
			if(type.equalsIgnoreCase("userfields"))
				writeFields(userFields_outfile);
			else if(type.equalsIgnoreCase("searchwords"))
				writeSearchWords(keywordSearch_outfile);
		} catch (FileNotFoundException e) {
			System.out.println("CustomField config file could not be written."+ e.getMessage());
		}
	}

	/**
	 *Writes database data to file, includes all tables, fields and values for
	 * the database.
	 */
	public void writeFields(String file) throws FileNotFoundException {
		String s = "<?xml version=\"1.0\" encoding= \"UTF-8\"?>\n<FIELDS>\n";
		PrintWriter out = new PrintWriter(new FileOutputStream(file));
		for (CustomField field : MainPage.fieldMatcher.getCustomFields()) {
			s += field.toXML();
		}
		s += "</FIELDS>\n";
		out.print(s);
		out.close();
	}
	
	public void writeSearchWords(String file) throws FileNotFoundException {
		String s = "<?xml version=\"1.0\" encoding= \"UTF-8\"?>\n<SEARCHWORDS>\n";
		PrintWriter out = new PrintWriter(new FileOutputStream(file));
		for (String word : MainPage.fieldMatcher.getCustomHeaderLineCheck()) {
			s += ("\t<WORD NAME=\""+word+"\"></WORD>\n");
		}
		s += "</SEARCHWORDS>\n";
		out.print(s);
		out.close();
	}
}
